﻿using System.Net.Sockets;
using MemoryPack;

namespace SeverMemory;

public class ClientController
{
    private Socket clientSocket;

    public ClientController(Socket socket)
    {
        clientSocket = socket;
        //启动一个线程来处理客户端请求
        Thread thread = new Thread(OnReceive);
        thread.Start();
    }

    private byte[] buffer = new byte[1024];
    //接收数据
    private void OnReceive(object? obj)
    {
        while (true)
        {
            //处理客户端请求
            int length = clientSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
            if (length>0)
            {
                //处理数据反序列化
                Account account = MemoryPackSerializer.Deserialize<Account>(buffer);
                Console.WriteLine("数据 账号："+account.username +", 密码："+account.password);
                AccountResult accountResult = new AccountResult();
                if (account.username=="admin" && account.password == "1234")
                {
                    accountResult.result = 1;
                    accountResult.msg = "登录成功";
                }
                else
                {
                    accountResult.result = 0;
                    accountResult.msg = "登录失败";
                }
                //序列化
                byte[] data = MemoryPackSerializer.Serialize(accountResult);
                //发送数据
                clientSocket.Send(data);
            }
        }
        
    }
}
[MemoryPackable]
public partial class Account
{
    public string username;
    public string password;
}

[MemoryPackable]
public partial class AccountResult
{
    public int result;
    public string msg;
}
